﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.ComponentModel;
using System.Net;

namespace Downloader
{
    public class DownManager
    {

        public event ProgressHandler Progress;
        public event CompletedHandler Complete;
        public event StartHandler Start;

        public string Destination_Dir { get; set;}
        private List<ServiceDown> Downloads;

        public  int TotalDownloads { get; private set;}
        public  int CurrentDownload { get; private set; }
        public  bool AutoDownload { get;  set; }

        public DownManager()
        {
            Downloads = new List<ServiceDown>();
            AutoDownload = false;
        }

        public DownManager(string Dst_dir)
        {
            Destination_Dir = Dst_dir;
            Downloads = new List<ServiceDown>();
            AutoDownload = false;
        }

        public void AddDownload(string Src_URI)
        {
            ServiceDown dwn = new ServiceDown();
            dwn.Source = Src_URI;
            dwn.Destination =  Destination_Dir;
            dwn.Progress += iProgressChanged;
            dwn.Complete += iCompleted;
            dwn.Start += iStart;
            Downloads.Add(dwn);
            TotalDownloads++;
        }

        private void iProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            if (Progress != null)
                Progress(sender, e);
        }

        private void iCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (Complete != null)
                Complete(sender, e);

            Downloads.Remove((ServiceDown)sender);
        }

        private void iStart(object sender)
        {
            if (Start != null)
                Start(sender);
        }

        public void InitDownloads()
        {
            if (CurrentDownload < TotalDownloads)
            {
                Downloads[CurrentDownload].Download();
                CurrentDownload++;
            }
        }
    }
}
